package com.ytq.share.service.impl;

import com.ytq.share.dto.CustomUserDTO;
import com.ytq.share.entity.User;
import com.ytq.share.entity.UserCoursePO;
import com.ytq.share.entity.UserItemPO;
import com.ytq.share.mapper.UserMapper;
import com.ytq.share.service.UserCourseService;
import com.ytq.share.service.UserItemService;
import com.ytq.share.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author yuantongqin
 * description:
 * 2020/12/7
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    UserCourseService userCourseService;

    @Autowired
    UserItemService userItemService;

    @Override
    public void saveUser(User userPO) {
//        userMapper.insert(userPO);
    }

    @Override
    public List<User> getUser(Long id) {
        return userMapper.getUserByUserId(id);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<User> getUserListByName(String name) {
        List<User> userListByName = userMapper.getUserListByName(name);
        userListByName.forEach(info->{
//            insertCourseList(info);
            String[] persons = {"zhangfei","guanyu","chaoyu","machao","huangzhong"};
            List<UserItemPO> collect = IntStream.range(1, 5).mapToObj(i -> {
                UserItemPO itemPO = new UserItemPO();
                itemPO.setUserId(info.getUserId());
                itemPO.setUserItemName(persons[new Random().nextInt(persons.length)]+""+i);
                return itemPO;
            }).collect(Collectors.toList());
            userItemService.batchInsert(collect);
        });
        return userListByName;
    }

    private void insertCourseList(User info) {
        String[] courses = {"Chinese","Math","English","chemistry"};
        List<UserCoursePO> collect = Arrays.stream(courses).map(item -> {
            UserCoursePO coursePO = new UserCoursePO();
            coursePO.setUserId(info.getUserId());
            coursePO.setCourseName(item);
            return coursePO;
        }).collect(Collectors.toList());
        userCourseService.batchInsert(collect);
    }

    @Override
    public List<CustomUserDTO> getAllUser() {
        return userMapper.getAllUser();
    }
}
